<template>
  <div class="app-container">
    <div class="filter-container">
        <el-cascader
            v-if="level == 1"
            class="filter-item"
            v-model="selectParent" :options="distributorsList"
                     :props="distributorsProps"
                     placeholder="所属经销商"
                     @change="getList"
                     style="width: 15%" clearable filterable></el-cascader>

<!--      <el-select v-model="listQuery.charge_id" filterable placeholder="套餐" class="filter-item" clearable-->
<!--                 @change="getList" style="width: 10%;margin-left:10px"-->
<!--      >-->
<!--        <el-option-->
<!--            v-for="item in chargeList"-->
<!--            :key="item.id"-->
<!--            :label="item.name"-->
<!--            :value="item.id"-->
<!--        >-->
<!--        </el-option>-->
<!--      </el-select>-->
<!--      <el-cascader v-model="selectAreas":options="options" :props="selectCityProps" class="filter-item"-->
<!--                   placeholder="按省市区筛选" @change="getList" style="width: 15%;margin-left: 5px" clearable filterable></el-cascader>-->

      <el-input
          class="filter-item"
          placeholder="输入关键字进行过滤"
          v-model="listQuery.keyword"
          style="width: 15%;margin-left: 5px"
      >
      </el-input>
      <!--      <el-input v-model="listQuery.title" placeholder="Title" style="width: 200px;" class="filter-item"-->
      <!--                @keyup.enter.native="handleFilter"-->
      <!--      />-->
      <!--      <el-select v-model="listQuery.importance" placeholder="Imp" clearable style="width: 90px" class="filter-item">-->
      <!--        <el-option v-for="item in importanceOptions" :key="item" :label="item" :value="item" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.type" placeholder="Type" clearable class="filter-item" style="width: 130px">-->
      <!--        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key" />-->
      <!--      </el-select>-->
      <!--      <el-select v-model="listQuery.sort" style="width: 140px" class="filter-item" @change="handleFilter">-->
      <!--        <el-option v-for="item in sortOptions" :key="item.key" :label="item.label" :value="item.key" />-->
      <!--      </el-select>-->
      <el-radio-group v-model="listQuery.is_active" style="margin-left: 5px"  class="filter-item" @change="getList">
        <el-radio-button label="">全部</el-radio-button>
        <el-radio-button :label="1">正常</el-radio-button>
        <el-radio-button :label="0">禁用</el-radio-button>
      </el-radio-group>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList"
                 style="margin-left: 10px"
      >
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate"
      >
        添加
      </el-button>
      <!--      <el-button v-waves :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download"-->
      <!--                 @click="handleDownload"-->
      <!--      >-->
      <!--        导出-->
      <!--      </el-button>-->
      <!--      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;" @change="tableKey=tableKey+1">-->
      <!--        审核-->
      <!--      </el-checkbox>-->
    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="ID" min-width="30">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="80" align="center" label="电站名称">
        <template slot-scope="scope">
          <el-link  type="success">{{scope.row.name}}</el-link>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>


      <el-table-column min-width="80" align="center" label="所属经销商">
        <template slot-scope="scope">
          <span v-if="scope.row.distributors">{{scope.row.distributors.name}}</span>
          <span type="info" v-else>暂无归属</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
<!--      <el-table-column min-width="80" align="center" label="套餐">-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.row.charge_name">{{scope.row.charge_name}}</span>-->
<!--          <span type="info" v-else>暂无</span>-->
<!--          &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column min-width="40" align="center" label="省份">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.province_name }}</span>-->
<!--          &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column min-width="40" align="center" label="城市">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.city_name }}</span>-->
<!--          &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column min-width="40" align="center" label="地区">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ scope.row.area_name }}</span>-->
<!--          &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column min-width="100" align="center" label="详细地址">
        <template slot-scope="scope">
          <span>{{ scope.row.address }}</span>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>
      <el-table-column min-width="40" align="center" label="设备数">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="查看设备详情" placement="top-start">
            <router-link :to="'/device/list?station_id='+scope.row.id" class="link-type">
             <el-button type="primary" size="mini">{{scope.row.device_count}}</el-button>
            </router-link>
          </el-tooltip>
          <!--          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>-->
        </template>
      </el-table-column>

<!--      <el-table-column min-width="50" align="center" label="退回金额">-->
<!--        <template slot-scope="scope">-->
<!--          <span v-if="scope.is_return_fee == 1">是</span>-->
<!--          <span v-else>否</span>-->
<!--          &lt;!&ndash;          <span>{{ scope.row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>&ndash;&gt;-->
<!--        </template>-->
<!--      </el-table-column>-->
=
      <el-table-column min-width="40" align="center" label="状态">
        <template slot-scope="scope">
          <el-switch
              v-model="scope.row.is_active"
              :active-value="1"
              :inactive-value="0"
              @change="changeStatus($event,scope.row.id)"

          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column min-width="60" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button type="primary" size="small" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" circle @click="del(scope.row.id)">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="getList"
    />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="40%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px"
               style="width: 90%; margin-left:5%;"
      >
        <el-form-item label="电站名称" prop="name">
          <el-input v-model="temp.name"  style="width: 80%"/>
        </el-form-item>
        <el-form-item label="所属经销商" v-if="level==1">
          <el-cascader v-model="editDistributor" ref="cascaderDistributors" :options="distributorsList"
                       :props="distributorsProps"
                       placeholder="请选择经销商"
                       @change="handleDistributorsChange"
                       filterable
                       style="width: 80%" clearable></el-cascader>
        </el-form-item>

<!--        <el-form-item label="省市区">-->
<!--          <el-cascader v-model="temp.areas" ref="cascaderAddr" :options="options" :props="cityProps"-->
<!--                       placeholder="请选择省市区" @change="handleAddrChange" style="width: 80%"></el-cascader>-->
<!--        </el-form-item>-->
        <el-form-item label="详细地址">
          <el-input v-model="temp.address"  style="width: 80%"/>
        </el-form-item>
        <el-form-item style="margin-bottom: 20px;" label="简介">
          <el-input v-model="temp.description" :rows="1" type="textarea" class="article-textarea" autosize
                    placeholder="请输入内容"
          />
<!--          <span v-show="contentShortLength" style="margin-left:10px" class="word-counter">{{ contentShortLength }}字</span>-->
        </el-form-item>
        <el-form-item label="电站图片">
          <el-upload
              action="/api/upload/base_image"
              list-type="picture-card"
              :file-list="fileList"
              :on-success="handleSuccess"
              :auto-upload="true"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <el-image
                  :src="file.url"
                  fit="contain"
                  style="height:146px;max-width:334px"
              >
              </el-image>
              <span class="el-upload-list__item-actions">
        <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file,fileList)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
            </div>
          </el-upload>
        </el-form-item>
<!--              <el-form-item label="退回剩余金额">-->
<!--                <el-radio-group v-model="temp.is_return_fee" size="small">-->
<!--                  <el-radio-button :label="1">是</el-radio-button>-->
<!--                  <el-radio-button :label="0">否</el-radio-button>-->
<!--                </el-radio-group>-->
<!--              </el-form-item>-->


              <el-form-item label="状态">
                <el-switch
                    v-model="temp.is_active"
                    :active-value="1"
                    :inactive-value="0"
                    active-text="开启"
                    inactive-text="关闭">
                </el-switch>
              </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <center>
          <el-button @click="resetForm">
            取消
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():createData()">
            提交
          </el-button>
        </center>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" :src="dialogImageUrl" alt="" fit="contain"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import {getList, create, del,changeStatus,selectCharge} from '@/api/station'
import { all } from '@/api/distributors'
// import { getMenus } from '@/api/menu'
import Pagination from '@/components/Pagination'
import store from '@/store'
import router from '@/router' // Secondary package based on el-pagination
import ImageCropper from '@/components/ImageCropper'
import PanThumb from '@/components/PanThumb'
import cityData from '@/assets/pca-code.json'

export default {
  name: 'StationList',
  components: {Pagination, ImageCropper, PanThumb},
  computed: {
    // contentShortLength() {
    //   return this.temp.description.length
    // },
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      editDistributor:'',
      disabled: false,
      fileList:[],
      // chargeList:[],
      // chargeList1:[],
      imagecropperShow: false,
      imagecropperKey: 0,
      menus: [],
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: '',
        // areas:'',
        distributor_id:'',
        is_active:'',
        // charge_id:''
      },
      selectAreas:'',
      selectParent:'',
      dialogImageUrl:'',
      dialogVisible:false,
      temp: {
        id: undefined,
        distributor_id: '',
        name: '',
        is_active: 1,
        description: '',
        remark:'',
        images:[],
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      filterText: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      rules: {
        name: [{required: true, message: '经销商名称不能为空', trigger: 'blur'}],
        owner_name: [{required: true, message: '负责人不能为空', trigger: 'blur'}],
        phone: [{required: true, message: '负责人手机号不能为空', trigger: 'blur'}],
        customer_service_phone: [{required: true, message: '客服电话不能为空', trigger: 'blur'}],
        // password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      addr: [],
      level:'',
      options: cityData,
      distributorsList: [],
      nowDistributor: '',
      disOptions: [],
      cityProps: {
        value: 'code',   // 指定选项的 值 为选项对象的某个属性值
        label: 'name',   // 指定选项 标签 为选项对象的某个属性值
        children: 'children'    //指定选项的 子选项 为选项对象的某个属性值
      },
      colors: [
        {color: '#f56c6c', percentage: 20},
        {color: '#e6a23c', percentage: 40},
        {color: '#5cb87a', percentage: 60},
        {color: '#1989fa', percentage: 80},
        {color: '#6f7ad3', percentage: 100}
      ],
      distributorsProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      selectCityProps: {
        value: 'code',   // 指定选项的 值 为选项对象的某个属性值
        label: 'name',   // 指定选项 标签 为选项对象的某个属性值
        children: 'children',    //指定选项的 子选项 为选项对象的某个属性值
        checkStrictly: true
      },
    }
  },
  watch: {

  },
  created() {
    this.level = this.$store.getters.introduction
    this.getList()
    this.getSelector()
  },
  methods: {

    handleRemove(file, fileList) {
      const key = this.fileList.indexOf(file)
      this.fileList.splice(key, 1)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleSuccess(file, fileList) {
      this.fileList.push(file.data)
    },
    changeStatus(val,id){
      changeStatus(val,id).then(response =>{
        this.$notify.success({
          title: '消息提示',
          message: response.msg,
          offset: 100
        })
        this.getList()
      })
    },
    getSelector(){
      all('all').then(response=>{
        this.distributorsList = response.data
      })
    },
    // getCharge(){
    //   if(this.selectParent && this.selectParent.length > 0){
    //     var distributor_id = JSON.stringify(this.selectParent)
    //   }else{
    //     var distributor_id = ''
    //   }
    //   selectCharge(distributor_id).then(response=>{
    //     this.chargeList = response.data
    //   })
    // },
    // editCharge(distributor_id){
    //   if(!distributor_id){
    //     if(this.temp.distributor_id && this.temp.distributor_id.length > 0){
    //       var distributor_id = JSON.stringify(this.temp.distributor_id)
    //     }else{
    //       var distributor_id = ''
    //     }
    //   }
    //   this.temp.charge_id = ''
    //   selectCharge(distributor_id).then(response=>{
    //     this.chargeList1 = response.data
    //   })
    // },
    increase() {
      this.temp.rate += 5;
      if (this.temp.rate > 100) {
        this.temp.rate = 100;
      }
    },
    decrease() {
      this.temp.rate -= 5;
      if (this.temp.rate < 0) {
          this.temp.rate = 0;
      }
    },
    handleAddrChange(e) {
      // 获取当前选中节点的数组
      let addrNode = this.$refs['cascaderAddr'].getCheckedNodes()[0]
      let addrText = addrNode.pathLabels
      this.temp.province_name = addrText[0]
      this.temp.city_name = addrText[1]
      this.temp.area_name = addrText[2]
    },
    handleDistributorsChange(e){
      // this.editCharge()
    },
    cropSuccess(resData) {
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.temp.avatar = resData.url
    },
    close() {
      this.imagecropperShow = false
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    getList() {
      // if(this.selectAreas && this.selectAreas.length > 0 ){
      //   this.listQuery.areas = JSON.stringify(this.selectAreas)
      // }else{
      //   this.listQuery.areas = ''
      // }
      if(this.selectParent && this.selectParent.length > 0){
        this.listQuery.distributor_id = JSON.stringify(this.selectParent)
      }else{
        this.listQuery.distributor_id = ''
      }
      // this.getCharge()
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        this.listLoading = false
      })
    },
    resetForm() {
      this.dialogFormVisible = false
      this.resetTemp()
    },
    handleCreate() {
      this.resetTemp()
      // this.getSelector()
      this.fileList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (Array.isArray(this.editDistributor)) {
          this.temp.distributor_id = this.editDistributor[this.editDistributor.length - 1];
        }else{
          if(!this.editDistributor){
            this.temp.distributor_id = 0
          }else{
            this.temp.distributor_id = this.editDistributor
          }
        }
        if (valid) {
          this.temp.images = this.fileList
          create(this.temp).then(response => {
            // this.list.unshift(this.temp)
            this.dialogFormVisible = false
            if (response.code == 200) {
              this.$notify.success({
                title: '成功',
                message: response.msg,
                type: 'success',
                duration: 2000
              })
              this.resetTemp()
              this.getList()
            } else {
              this.$notify.error({
                title: '失败',
                message: response.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      // this.getSelector()
      // this.editCharge('['+row.distributor_id+']')
      if (typeof row.images === 'string' && row.images) {
        this.fileList =JSON.parse(row.images)
      }else{
        this.fileList = row.images
      }
      if(this.fileList == null || !this.fileList){
        this.fileList = []
      }
      this.editDistributor =row.distributor_id
      setTimeout(() => {
        this.temp.station_id = row.station_id
      }, 500);
      this.temp = Object.assign({}, row) // copy obj
      // this.temp.areas = [row.province_id+'',row.city_id+'',row.area_id+'']
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    del(id) {
      this.$confirm('确认要删除该条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(id).then(response => {
          // this.list.unshift(this.temp)
          if (response.code == 200) {
            this.$notify.success({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            this.resetTemp()
            this.getList()
          } else {
            this.$notify.error({
              title: '失败',
              message: response.msg,
              duration: 2000
            })
          }
        })
      }).catch(() => {

      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        distributor_id: '',
        // areas: '',
        // charge_id:'',
        name: '',
        is_active: 1,
        description: '',
        remark:'',
        is_return_fee:1,
        // province_name:'',
        // city_name:'',
        // area_name:'',
        images:''
      }
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
<style scoped>
.avatar {
  width: 200px;
  height: 200px;
  border-radius: 50%;
}
</style>
<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
